package network;

import itdb1.commun.*;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

import controller.GUIController;

public class UDPTransmitter {

	protected DatagramSocket sock;
	protected DatagramPacket packet;
	protected int port;
	
	private GUIController guicontroller;
	
	public UDPTransmitter(NetworkSignal m, int port) {
		this.port = port;
		this.guicontroller = GUIController.getInstance();
		String debugmessage = "UDPTransmitter > ";
		InetAddress addr;
		
		byte[] contentDatagram = null;
		ByteArrayOutputStream byteOuts = null;
		ObjectOutputStream out = null;
		
		try
		{
			byteOuts = new ByteArrayOutputStream();
			out = new ObjectOutputStream( byteOuts );
			
			if(m.getClass() == Hello.class)
			{
				out.writeObject( (Hello) m);
				debugmessage += "Hello";
				addr = InetAddress.getByName("255.255.255.255");
			}
			else if(m.getClass() == HelloAck.class)
			{
				out.writeObject( (HelloAck) m);
				debugmessage += "HelloAck";
				addr = m.getFromIp();
			}
			else if(m.getClass() == Message.class)
			{
				out.writeObject( (Message) m);
				debugmessage += "Message";
				addr = m.getFromIp();
			}
			else if(m.getClass() == HeartBeats.class)
			{
				out.writeObject( (HeartBeats) m);
				debugmessage += "HeartBeats";
				addr = m.getFromIp();
			}
			else if(m.getClass() == Bye.class)
			{
				out.writeObject( (Bye) m);
				debugmessage += "Bye";
				addr = m.getFromIp();
			}
			else
			{
				throw new ClassNotFoundException();
			}
		
			contentDatagram = byteOuts.toByteArray();
			
			packet = new DatagramPacket( contentDatagram, contentDatagram.length, addr, port );

			(new DatagramSocket()).send(packet);
			
			debugmessage += " has been sent to " + addr.getHostAddress() + ":" + port + "\n" ;
			guicontroller.writeDebugScreen(debugmessage);
		}
		catch(IOException ioException)
		{
			ioException.printStackTrace();
		}
		catch(ClassNotFoundException e)
		{
			guicontroller.writeDebugScreen("UDPTransmitter > cannot send this kind of message !\n");
		}
		finally
		{
			try
			{
				out.close();
				byteOuts.close();
			}
			catch(IOException ioException)
			{
				ioException.printStackTrace();
			}
		}
	}
}
